// pages/activity/activity.js
const app = getApp()

Page({
  data: {
    showPointsModal: false,
    remote_src: app.globalData.remote_src,
    userInfo: {},
    activeTab: 'activity',
    points: 9,
    currentTab: 'wantToGo',
    wantToGoCount: 0,
    registeredCount: 0,
    createdCount: 0,
    finishedCount: 0,
    wantToGoList: [
    ],
    registeredList: [
  
    ],
    finishedList: [

    ],
    createdList: [
      
    ],
    showFilterModal: false,
    filterType: 'all',
    filterArea: 'all', 
    filterPeople: 'all',
  },
  goToAuth: function() {
    // 如果用户已认证，不执行任何操作
    if (this.data.userInfo.is_auth) {
      return;
    }
    // 跳转到认证页面
    wx.navigateTo({
      url: '/pages/cerficate/cerficate'
    })
  },
  viewPointsRecord: function() {
    wx.navigateTo({
      url: '/pages/mine/qiyu_record/qiyu_record',
    })
    this.setData({
      showPointsModal: false
    });
  },
// ... existing code ...
  // onShow: function () {
  //   // 获取用户信息 
  //   if (app.globalData.userInfo) {
  //     let userInfo =  JSON.parse(JSON.stringify(app.globalData.userInfo));
  //     if (userInfo.interests) {
  //       try {
  //         userInfo.interests = JSON.parse(userInfo.interests);
  //       } catch (e) {
  //         console.log('解析兴趣字符串失败:', e);
  //       }
  //     }
  //     this.setData({
  //       userInfo: userInfo,
  //       points: userInfo.points,
  //     })
  //     console.log('用户信息:', app.globalData.userInfo)
  //   } else {
  //     // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
  //     app.userInfoReadyCallback = res => {
  //       this.setData({
  //         userInfo: res
  //       })
  //     }
  //   }
  //   // 获取活动列表数据
  //   this.getActivityList()
  // },
  onShow: function() {
        // 获取用户信息
        if (app.globalData.userInfo) {
          let userInfo =  JSON.parse(JSON.stringify(app.globalData.userInfo));
          if (userInfo.interests) {
            try {
              userInfo.interests = JSON.parse(userInfo.interests);
            } catch (e) {
              console.log('解析兴趣字符串失败:', e);
            }
          }
          this.setData({
            userInfo: userInfo,
            points: userInfo.points,
          })
          console.log('用户信息:', app.globalData.userInfo)
        } else {
          // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          app.userInfoReadyCallback = res => {
            this.setData({
              userInfo: res
            })
          }
        }
        
        // 加载收藏的活动列表
        this.loadWantToGoList();
        this.loadCreatedList();
        this.loadRegisteredList();
        this.loadFinishedList();
  },
  onLoad: function (options) {

  },
  
  // 切换顶部导航栏
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      activeTab: tab
    })
  },
  
  // 切换活动标签页
  changeTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ currentTab: tab });
    // 根据不同标签加载对应数据
    switch(tab) {
      case 'wantToGo':
        this.loadWantToGoList();
        break;
      case 'registered':
        this.loadRegisteredList();
        break;
      case 'created':
        console.log('created')
        this.loadCreatedList();
        break;
      case 'finished':
        this.loadFinishedList();
        break;
    }
  },
  // 加载想去的活动列表
  loadWantToGoList() {
    const websiteUrl = getApp().globalData.onlineService + '/api/fav/fav';
    
    // 构建筛选参数
    let filterParams = {
      page: 1,
      page_size: 10
    };
    
    // 添加筛选条件
    if (this.data.filterType !== 'all') {
      filterParams.type = this.data.filterType;
    }
    if (this.data.filterArea !== 'all') {
      filterParams.area = this.data.filterArea;
    }
    if (this.data.filterPeople !== 'all') {
      filterParams.people = this.data.filterPeople;
    }
    
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: filterParams,
      success: (res) => {
        console.log(res.data)
        if (res.data.code === 200) {
          // 转换数据结构以匹配前端需要的格式
          const formattedList = res.data.msg.list.map(item => ({
            id: item.activity_id,
            name: item.activity_name,
            content: item.activity_content,
            type: item.activity_type,
            images: item.activity_images,
            fee: item.activity_fee,
            status: item.activity_status,
            start_time: item.activity_start_time,
            end_time: item.activity_end_time,
            people_number: item.activity_people_number,
            people_age: item.activity_people_age,
            created_user_id: item.created_user_id,
            address: item.address,
            c_time: item.created_at
          }));
          
          this.setData({
            wantToGoList: formattedList,
            wantToGoCount: res.data.msg.total
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取收藏列表失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  // 加载已报名活动列表
  loadRegisteredList() {
    const websiteUrl = getApp().globalData.onlineService + '/api/reg/reg';
    
    // 构建筛选参数
    const filterParams = {
      page: 1,
      page_size: 10
    };
    
    // 添加筛选条件
    if (this.data.filterType && this.data.filterType !== '全部') {
      filterParams.type = this.data.filterType;
    }
    if (this.data.filterArea && this.data.filterArea !== '全部') {
      filterParams.area = this.data.filterArea;
    }
    if (this.data.filterPeople && this.data.filterPeople !== '全部') {
      filterParams.people = this.data.filterPeople;
    }
    
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}` 
      },
      data: filterParams,
      success: (res) => {
        if (res.data.code === 200) {
          console.log(res.data)
          this.setData({
            registeredList: res.data.msg.list,
            registeredCount: res.data.msg.total
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取报名列表失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  // 加载我发起的活动列表
  loadCreatedList() {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity';
    console.log(websiteUrl, getApp().globalData.userInfo.token)

    // 构建筛选参数
    const filterParams = {
      user_id: getApp().globalData.userInfo.id,
      page: 1,
      page_size: 10,
      status: '0,1'
    };
    
    // 添加筛选条件
    if (this.data.filterType && this.data.filterType !== 'all') {
      filterParams.type = this.data.filterType;
    }
    if (this.data.filterArea && this.data.filterArea !== 'all') {
      filterParams.area = this.data.filterArea;
    }
    if (this.data.filterPeople && this.data.filterPeople !== 'all') {
      filterParams.people = this.data.filterPeople;
    }
    
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}` 
      },
      data: filterParams,
      success: (res) => {
        if (res.data.code === 200) {
          console.log(res.data.data);
          this.setData({
            createdList: res.data.data.activities,
            createdCount: res.data.data.total
          });
          console.log(this.data.createdList);
          wx.showToast({
            title: '加载成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取我发起的活动失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
   // 加载已结束的活动列表
  loadFinishedList() {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity_finish';
      // 构建筛选参数
    const filterParams = {
      page: 1,
      page_size: 100
    };
    
    // 添加筛选条件
    if (this.data.filterType && this.data.filterType !== 'all') {
      filterParams.type = this.data.filterType;
    }
    if (this.data.filterArea && this.data.filterArea !== 'all') {
      filterParams.area = this.data.filterArea;
    }
    if (this.data.filterPeople && this.data.filterPeople !== 'all') {
      filterParams.people = this.data.filterPeople;
    }
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}` 
      },
      data: filterParams,
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            finishedList: res.data.data,  // 已报名且已结束的活动
            finishedCount: res.data.data.length
          });
           wx.showToast({
            title: '加载成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: res.data.msg || '获取已结束活动失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  goToActivityDetail(e) {
    const activityId = e.currentTarget.dataset.id;
    if(this.data.currentTab === "wantToGo" || this.data.currentTab === "registered" || this.data.currentTab === "finished"){
      wx.navigateTo({
        url: `/pages/home/activity/activity?id=${activityId}`,
        fail: (err) => {
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }else {
      let activity = null;
      if(this.data.currentTab === 'created') {
        activity = this.data.createdList.find(item => item.id === activityId);
      }else if(this.data.currentTab === 'finished') {
        activity = this.data.finishedList.find(item => item.id === activityId);
      }else if(this.data.currentTab === 'registered') {
        activity = this.data.registeredList.find(item => item.id === activityId);
      }else if(this.data.currentTab === 'wantToGo') {
        activity = this.data.wantToGoList.find(item => item.id === activityId);
      }
      // 将活动对象转换为查询字符串
      const queryString = Object.keys(activity)
        .map(key => {
          let value;
          if (key === 'address') {
            value = encodeURIComponent(JSON.stringify(activity[key]));
          } else if (key === 'images') {
            value = encodeURIComponent(JSON.stringify(activity[key])); // 将图片数组转为 JSON 字符串
          } else {
            value = encodeURIComponent(activity[key]);
          }
          return `${key}=${value}`;
        })
        .join('&');
      wx.navigateTo({
        url: `/pages/mine/my_created_activity/my_created_activity?${queryString}`
      });
     }
  },
  // 查看更多积分
  viewMorePoints: function() {
    this.setData({
      showPointsModal: true
    });
  },
  closePointsModal() {
    this.setData({
      showPointsModal: false
    });
  },
  // 关注用户
  followUser: function() {
    wx.showToast({
      title: '关注成功',
      icon: 'success'
    })
  },
  
  // 获取活动列表
  getActivityList: function() {
    // 这里可以添加从服务器获取活动列表的代码
    // wx.request({
    //   url: app.globalData.offlineService + '/api/activities',
    //   method: 'GET',
    //   success: (res) => {
    //     if (res.data.status === 'success') {
    //       this.setData({
    //         wantToGoList: res.data.wantToGo,
    //         registeredList: res.data.registered,
    //         finishedList: res.data.finished,
    //         wantToGoCount: res.data.wantToGo.length,
    //         registeredCount: res.data.registered.length
    //       })
    //     }
    //   }
    // })
  },
  goToSettings: function() {
    wx.navigateTo({
      url: '/pages/mine/my_setting/my_setting',
    })
  },
  // 显示筛选弹框
showFinishedFilter() {
  this.setData({
    showFilterModal: true
  });
},

// 关闭筛选弹框
closeFilterModal() {
  this.setData({
    showFilterModal: false
  });
},

// 按类型筛选
filterByType(e) {
  const type = e.currentTarget.dataset.type;
  this.setData({
    filterType: type
  });
},

// 按区域筛选
filterByArea(e) {
  const area = e.currentTarget.dataset.area;
  this.setData({
    filterArea: area
  });
},

// 按人数筛选
filterByPeople(e) {
  const people = e.currentTarget.dataset.people;
  this.setData({
    filterPeople: people
  });
},

// 重置筛选
resetFilter() {
  this.setData({
    filterType: 'all',
    filterArea: 'all',
    filterPeople: 'all'
  });
},

// 确认筛选
confirmFilter() {
  // 根据当前标签页重新加载对应数据
  switch(this.data.currentTab) {
    case 'wantToGo':
      this.loadWantToGoList();
      break;
    case 'registered':
      this.loadRegisteredList();
      break;
    case 'created':
      this.loadCreatedList();
      break;
    case 'finished':
      this.loadFinishedList();
      break;
  }
  
  this.setData({
    showFilterModal: false
  });
},

// 应用筛选
applyFilters() {
  let filteredList = this.data.originalFinishedList || this.data.finishedList;
  
  // 按类型筛选
  if (this.data.filterType !== 'all') {
    filteredList = filteredList.filter(item => item.type === this.data.filterType);
  }
  
  // 按区域筛选
  if (this.data.filterArea !== 'all') {
    filteredList = filteredList.filter(item => 
      item.address && item.address.address && item.address.address.includes(this.data.filterArea)
    );
  }
  
  // 按人数筛选（需要根据实际数据结构调整）
  if (this.data.filterPeople !== 'all') {
    // 这里需要根据您的数据结构来实现人数筛选逻辑
    // 例如：filteredList = filteredList.filter(item => /* 人数筛选逻辑 */);
  }
  
  this.setData({
    finishedList: filteredList
  });
}
})